<template>
  <div class="search-result">
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" error.sync="error"  error-text="请求失败，点击重新加载"  @load="onLoad">
      <van-cell v-for="(article,index) in list" :key="index" :title="article.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search.js'
export default {
  name: 'searchResult',
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      per_page: 20,
      error:false
    }
  },
  methods: {
    async onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // 1.发送请求
      // 2.设置数据给List
      // 3.loading = false
      // 4.判断是否结束
      //   4.1  没有  page++
      //   4.2. 结束  finished: true,
      // 5.出现错误
      // 6.头部定位

      try {
        // 1.发送请求
        const { data: res } = await getSearchResult({
          page: this.page,
          per_page: this.per_page,
          q: this.searchText,
        })
        // console.log(res);
        // 2.设置数据给List
        this.list = res.data.results

        // 3.设置加载为loading = false 加载完成
        this.loading = false;

        // 4.判断是否结束
        if(res.data.results.length){
            this.page++
        }else {
            this.finished = true
        }

      } catch (err) {
          this.error = true;
          this.loading = false;
      }
    },
  },
  created() {},
}
</script>

<style lang="" scoped>
</style>